import { app, shell, BrowserWindow, ipcMain, Tray, Menu, globalShortcut, dialog } from 'electron'
import { join } from 'path'
import fs from 'fs'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import redisClient from './redis'

let mainWindow: BrowserWindow | null
let tray: Tray

// 创建窗口
function createWindow(): void {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    resizable: false,
    show: false,
    autoHideMenuBar: true,
    frame: false,
    ...(process.platform === 'linux' ? { icon } : { icon }),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  // 内容加载完毕后显示主窗口
  mainWindow.on('ready-to-show', () => {
    mainWindow?.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// 创建系统托盘
function createTray() {
  tray = new Tray(icon)
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示主界面',
      click() {
        mainWindow?.setFullScreen(true)
        mainWindow?.show()
      }
    },
    {
      label: '退出',
      click() {
        app.quit()
      }
    }
  ])
  tray.setToolTip('简单猫-餐饮系统')
  tray.setContextMenu(contextMenu)
  tray.on('double-click', () => mainWindow?.show())
}

// 创建全局键盘快捷键
function createShortcut() {
  globalShortcut.register('F11', () => mainWindow?.webContents.openDevTools())
}

// 创建渲染进程到主进程的通信
function createIpc() {
  ipcMain.on('ping', () => console.log('pong'))

  // 更改窗口大小
  ipcMain.on('size', (_, obj: { width: number; height: number }) => {
    mainWindow?.setSize(obj.width, obj.height, true)
  })

  // redis连接
  ipcMain.on('redis', async (_, obj: object) => {
    redisClient.getClient()?.set('electron-name', JSON.stringify(obj))
    const val = await redisClient.getClient()?.get('electron-name')
    // redisClient.getClient()?.publish('event-name', 'dsdsdsadsa')
    console.log(val)
  })

  // 保存配置文件
  ipcMain.on('save', (_, obj: unknown) => {
    const filepath = join('./', 'appsettings.json')
    // 写入文件
    fs.writeFileSync(filepath, JSON.stringify(obj))

    // 读取文件
    const data = fs.readFileSync(filepath)
    console.log(JSON.parse(data.toString()))
  })

  // 关闭应用时
  ipcMain.on('close', async () => {
    const index = await dialog.showMessageBox({
      type: 'info',
      title: '提示',
      defaultId: 0,
      message: '确定要关闭应用吗？',
      buttons: ['最小化到托盘', '直接退出']
    })
    if (index.response === 0) {
      mainWindow?.hide()
    } else {
      mainWindow = null
      app.quit()
    }
  })
}

// 创建主进程到渲染进程的通信
function createRender() {
  let num = 0
  const a = () => {
    num++
    // 窗口已销毁，则退出
    if (!mainWindow || mainWindow?.isDestroyed()) return
    mainWindow?.webContents.send('update-number', num)
    setTimeout(() => {
      a()
    }, 1000)
  }
  a()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.jiandanmaokeji')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC
  createIpc()

  // IPC
  createRender()

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  // 全局快捷键
  createShortcut()
  // 系统托盘
  createTray()
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
    mainWindow = null
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
